package controllers;

import activity.ActivityProduct;
import enums.ProductStatus;
import enums.ReviewStatus;
import helper.AliyunOssUploader;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.merchant.enums.VerifyState;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.mvc.Controller;
import play.mvc.With;
import product.Product;
import product.ProductImage;
import product.type.ProductType;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by youliangcheng on 17/6/21.
 */
@With(LoginInCtrl.class)
public class ProductCtrl extends Controller {
    public static Integer PAGE_SIZE = 10;
    //产品列表页
    public static void index(Long typeId) {
        Logger.info("typeId==================================== : %s " , 0);
        Merchant merchant = LoginInCtrl.getMerchant();
        //        Merchant merchant = Merchant.findByMerchantId(1);
        long merchantId = merchant.id;
        List<ProductType> typeList = ProductType.loadAllParentType(0l);
        ProductType typeIndex = ProductType.loadFirParentType(0l);
        Logger.info("typeIndex.id==================================== : %s " , typeIndex.id);
        render(typeList, merchantId, typeIndex);
    }

    /**
     * 二级分类
     * @param id
     */
    public static void secondLevel(long id){
        Map<String , Object> resultMap = new HashMap<>();
        if(id == 0){
            resultMap.put("success",false);
            resultMap.put("list", new ArrayList<ProductType>());
            renderJSON(resultMap);
        }
        List<ProductType> secondLevel = ProductType.findChildNode(id);
        if(secondLevel == null || secondLevel.size() == 0){
            resultMap.put("success",false);
            resultMap.put("list", new ArrayList<ProductType>());
            renderJSON(resultMap);
        }
        resultMap.put("success",true);
        resultMap.put("list",secondLevel);
        renderJSON(resultMap);
    }


    //加载产品列表
    public static void loadTypeProductList(long id,Integer pageNum , Integer infinite) {
        pageNum = pageNum == null ? 0 : pageNum;
        int firstPage = (pageNum-1)*PAGE_SIZE;
        infinite = infinite == null ? 0 : infinite;
        Logger.info("typeId==================================== : %s " , id);
        Map<String, Object> resultMap = new HashMap<>();

        Merchant merchant = LoginInCtrl.getMerchant();
        //        Merchant merchant = Merchant.findByMerchantId(1);
        List<Product> productList = new ArrayList<>();
        if (id > 0) {
            Logger.info("firstPage=================== : %s " , firstPage);
            productList = Product.getProductListByTypeAndMerchant(id,merchant.id);
        }else{
            ProductType productType = ProductType.loadFirParentType(0);
            productList = Product.getProductListByTypeAndMerchant(productType.id,merchant.id);
        }

        Logger.info("productList==================================== : %s " , productList.size());
        resultMap.put("infinite" , infinite);
        resultMap.put("success",true);
        resultMap.put("productList",productList);
        renderJSON(resultMap);
    }

    //产品详情页
    public static void detail(Long id) {
        Merchant merchant = LoginInCtrl.getMerchant();
        //    Merchant merchant = Merchant.findByMerchantId(7);
        long merchantId = merchant.id;
        List<ProductImage> imageList =  new ArrayList<>();
        List<ProductType> typeList = new ArrayList<>();
        Product product = new Product();
        if (id != null && id > 0){
            product = Product.findByProductId(id);
            imageList = ProductImage.loadByProductId(product.id);
            typeList = ProductType.loadAllParentType(product.parentType.id);
        }
        List<ProductType> parentList = ProductType.loadAllParentType(0l);
        String mainImage = product.mainImage;
        Logger.info("imageList.size()=========== :%s",imageList.size());
        render(product, parentList , mainImage,imageList,typeList);
    }

    //加载图片
    public static void uploadImg(String imgData,String imgPath ){
        Logger.info("imgPath=========== :%s",imgPath);
        Logger.info("imgData=========== :%s",imgData);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] result = decoder.decodeBuffer(imgData.split(",")[1]);

            InputStream sbs = new ByteArrayInputStream(result);

            String realPath = AliyunOssUploader.uploadPublicFile(sbs, imgPath, result.length);
            Logger.info("realPath=========== :%s",realPath);
            renderJSON("{\"realPath\":\""+realPath+"\"}") ;
        } catch (IOException e) {
            Logger.info("Log home/uploadImg error :" + e.getMessage());
            e.printStackTrace();
        }

        renderJSON("{\"realPath\":\"\"}") ;
    }



    //保存产品信息
    public static void savePro(Long  id,
                               String name ,
                               List<String> imageArray,
                               String mainImage ,
                               Long typeId ,
                               Long parentTypeId,
                               String spec ,
                               String unit ,
                               Double merchantPrice ,
                               ProductStatus productSatus ,
                               Double stock ,
                               Double oldPrice ,
                               String pcContent
                             ) {
        Logger.info("name=========== :%s",name);
        Map<String , Object> resultMap = new HashMap<>();
        Product product = new Product();

        Merchant merchant = LoginInCtrl.getMerchant();
        Logger.info("merchant.name=========== :%s",merchant.name);
        if(id != null && id > 0) {
            product = Product.findByProductId(id);
            if(product == null){
                resultMap.put("success",false);
                resultMap.put("msg","商品信息不存在,可能已经被删除 , 修改失败!");
                renderJSON(resultMap);
            }
           product.modifyAt = new Date();
//            product.deleted = DeletedStatus.UN_DELETED ;
        }else {
            product.deleted = DeletedStatus.UN_DELETED ;
            product.createdAt = new Date();
            product.productStatus = ProductStatus.DOWN;
            product.merchant = merchant ;
        }

        ProductType productType = ProductType.findByTypeId(typeId);
        if(productType == null){
            resultMap.put("success",false);
            resultMap.put("msg","分类信息不存在,可能已经被删除 , 保存失败!");
            renderJSON(resultMap);
        }
        ProductType parentType = ProductType.findByTypeId(parentTypeId);
        if(parentType == null){
            resultMap.put("success",false);
            resultMap.put("msg","分类信息不存在,可能已经被删除 , 保存失败!");
            renderJSON(resultMap);
        }
        if(id != null && id > 0) {
            ProductImage image = ProductImage.loadFirstByProductId(product.id);
            if(image != null){
                ProductImage.delProductImg(product.id);
            }
        }
        product.oldPrice = oldPrice;
        product.name = name;
        product.spec = spec;
        product.unit = unit;
        product.merchantPrice = merchantPrice;
        product.pcContent = pcContent;
        product.productType = productType;
        product.parentType = parentType;
        product.productStatus = productSatus ;
        product.merchant = merchant;
        product.stock = stock ;
        product.reviewStatus = ReviewStatus.NORMAL;
        product.mainImage = StringUtils.isNotBlank(mainImage) ? mainImage  : "/public/sui/images/nopic.gif";
        if(product.productStatus == ProductStatus.DOWN){
            ActivityProduct.deletedByProductId(product.id);
         //   AliyunOpenSearch.uploadProductByRiZhi(product);
        }
        product.save();
        for(int i = 0; i<imageArray.size();i++){
            ProductImage productImage = new ProductImage();
            productImage.product = product;
            productImage.imgPath = imageArray.get(i);
            Logger.info("productImage.imgPath=========== :%s",productImage.imgPath);
            productImage.save();
        }
        product.save();
        if(merchant.verifyState == VerifyState.PASS){
          //   AliyunOpenSearch.uploadProductByRiZhi(product);
        }
        resultMap.put("success",true);
        resultMap.put("typeId",typeId);
        renderJSON(resultMap);
    }

    //删除产品
    public static void delProduct(long id) {
        Product product = Product.findByProductId(id);
        Map<String, Object> resultMap = new HashMap<>();
        if (product == null) {
            resultMap.put("success", false);
            resultMap.put("msg", "商品不存在,可能已经被删除!");
            renderJSON(resultMap);
        }

        product.deleted = DeletedStatus.DELETED;
        product.save();
      //  AliyunOpenSearch.uploadProductByRiZhi(product);
        ActivityProduct.deletedByProductId(product.id);
        resultMap.put("success", true);
        if (product.productType != null)
            resultMap.put("typeId", product.productType.id);
        flash.put("msg","删除成功!");
        renderJSON(resultMap);

    }

    //加载图片
    public static void uploadLogo(String imgData,String imgPath ){
        Logger.info("imgPath=========== :%s",imgPath);
        Logger.info("imgData=========== :%s",imgData);
        Map<String , Object> resultMap = new HashMap<>();
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] result = decoder.decodeBuffer(imgData.split(",")[1]);
            InputStream sbs = new ByteArrayInputStream(result);
            String realPath = AliyunOssUploader.uploadPublicFile(sbs, imgPath, result.length);
            resultMap.put("realPath",realPath);
            Logger.info("realPath=========== :%s",realPath);
            renderJSON(resultMap) ;
        } catch (IOException e) {
            Logger.info("Log home/uploadImg error :" + e.getMessage());
            e.printStackTrace();
        }

        renderJSON("{\"realPath\":\"\"}") ;
    }

    //加载产品列表
    public static void getProductByType(long typeId) {

        Logger.info("typeId==================================== : %s " , typeId);
        Map<String , Object> resultMap = new HashMap<>();
        Merchant merchant = LoginInCtrl.getMerchant();
        List<Product> productList = new ArrayList<>();
        Logger.info("merchant==================================== : %s " , merchant.id);
        if (typeId > 0) {
            productList = Product.loadByTypeAndMerchant(typeId,merchant.id);
            Logger.info("productList==================================== : %s " , productList.size());
        }

        resultMap.put("success",true);
        resultMap.put("productList",productList);
        renderJSON(resultMap);
    }

}
